package com.heartline.init;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONReader;
import com.blade.Blade;
import com.blade.event.BeanProcessor;
import com.blade.ioc.annotation.Bean;
import com.blade.ioc.annotation.Inject;
import com.blade.ioc.annotation.Order;
import com.heartline.task.PushSchedule;
import com.heartline.util.StringUtils;
import io.github.biezhi.anima.Anima;
import lombok.extern.slf4j.Slf4j;
import org.sql2o.Sql2o;

import java.io.*;
import java.net.URL;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import static io.github.biezhi.anima.Anima.select;


@Order(1)
@Bean
@Slf4j
public class WebProcessor implements BeanProcessor {

    @Inject
    PushSchedule schedule;

    @Override
    public void processor(Blade blade) {

        loadMeizuCitys("json/Meizu_city.json");
        Env.setEnvironment(blade.environment());
        log.info("enviroment success");
        // SQLite
        sqlite();
        log.info("load datasource success");
        //init run task
        schedule.calandar_task();
        log.info("start task success");
        log.info("init complete");
    }


    private void loadMeizuCitys(String path) {
        URL url = getClass().getClassLoader().getResource(path);
        File file = new File(url.getFile());
        String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());

        if (file.isFile() && prefix.equalsIgnoreCase("json")) {
            try {
                JSONReader reader = new JSONReader(new FileReader(file));
                JSONArray array = reader.readObject(JSONArray.class);
                array.forEach((Object n) -> {
                    JSONObject city = (JSONObject) JSON.toJSON(n);
                    Env.putMeizuCity(city.getString("countyname"), city.getInteger("areaid"));
                });
                log.info("加载资源文件 - {} 成功", file.getName());
            } catch (Exception e) {
                log.error("资源文件 - {} 无法加载", file.getName(), e);
                System.exit(-1);
            }
        }
    }

    //初始化Sqlite
    private void sqlite() {
        try {
            Sql2o sql2o = Anima.open("jdbc:sqlite:./main.db").getSql2o();
            sql2o.setIsolationLevel(java.sql.Connection.TRANSACTION_SERIALIZABLE);
            int count = select().bySQL(Integer.class, "SELECT count(*) FROM sqlite_master WHERE type=? AND name=?", "table", "t_options").one();
            if (count == 0) {
                log.info("数据库未创建, 开始初始化...");
                List<String> sqlFile = new ArrayList<>();
                String cp = WebProcessor.class.getClassLoader().getResource("").getPath();
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(cp + "main.sql"), "UTF-8"));
                String str;
                while ((str = br.readLine()) != null) {
                    if (StringUtils.isNotBlank(str) && !str.startsWith("-") && !str.startsWith("#")) {
                        sqlFile.add(str);
                    }
                }
                Statement stmt = sql2o.getConnectionSource().getConnection().createStatement();
                for (String sql : sqlFile) {
                    sql = sql.trim();
                    if (sql != null && !sql.equals(""))
                        stmt.addBatch(sql);
                }
                stmt.executeBatch();
                log.info("初始化数据库成功");
            }
        } catch (Exception e) {
            log.error("init database error!", e);
            System.exit(-1);
        }
    }
}
